extends Node

const HIT_FLASH_MATERIAL := preload("uid://dv0n6vukryhxx")

@export var healrh_component: HealthComponent
@export var sprite: Node2D

var last_percent:float = 1.0
var hit_flash_tween: Tween


func _ready() -> void:
	healrh_component.health_changed.connect(on_health_change.bind())
	sprite.material = HIT_FLASH_MATERIAL.duplicate()
	
func on_health_change(cur_percent:float) -> void:
	if last_percent < cur_percent: return
	last_percent = cur_percent
	if hit_flash_tween != null && hit_flash_tween.is_valid():
		hit_flash_tween.kill()
	
	flash()

func flash() -> void:
	(sprite.material as ShaderMaterial).set_shader_parameter("lerp_percent", 1.0)
	hit_flash_tween = create_tween()
	hit_flash_tween.tween_property(sprite.material, "shader_parameter/lerp_percent", 0.0, .25)\
	.set_ease(Tween.EASE_IN).set_trans(Tween.TRANS_CUBIC)
